package com.heer.gymnasium.module.login.views;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bigkoo.svprogresshud.SVProgressHUD;
import com.heer.amap.utils.ToastUtil;
import com.heer.gymnasium.AppHelper;
import com.heer.gymnasium.api.ResponseData.ApiResponse;
import com.heer.gymnasium.api.callback.BaseCallback;
import com.heer.gymnasium.api.SignHelper;
import com.heer.gymnasium.R;
import com.heer.gymnasium.api.constants.IConstants;
import com.heer.gymnasium.base.BaseActivity;
import com.heer.gymnasium.module.login.beans.LoginBean;
import com.heer.gymnasium.module.login.beans.LoginResponseBean;
import com.heer.gymnasium.module.login.beans.WxLoginBean;
import com.heer.gymnasium.module.main.views.MainActivity;
import com.heer.gymnasium.util.ActivityStartUtils;
import com.heer.gymnasium.util.Session;
import com.heer.gymnasium.util.StringUtils;
import com.heer.gymnasium.util.SystemUtils;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.zhihuiyun.library.utils.L;

import java.io.IOException;
import java.lang.ref.WeakReference;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import retrofit2.Call;
import retrofit2.Response;

/**
 * Created by heer on 17/3/28.
 */

public class LoginActivity extends BaseActivity {
    public static final String TIME_OUT = "登录信息已过期";

    private final static int RES_ID_CODE_BTN = R.id.layout_login_code_tv;
    private final static int RES_ID_CODE_ET = R.id.layout_login_code_et;


    @BindView(R.id.layout_login_phone_et)
    EditText editAccount;
    @BindView(R.id.layout_login_submit_tv)
    TextView btnLogin;
    @BindView(R.id.layout_login_wechat_iv)
    ImageView btnWxLogin;
    @BindView(RES_ID_CODE_BTN)
    TextView tvCode;
    @BindView(RES_ID_CODE_ET)
    EditText etCode;

    private IWXAPI api;
    public static Handler mHandler;
    private String mUnionId;

    private int count = 0;//验证码计数器
    private MyHandler myHandler;
    private boolean runningOne = false;
    private LoginActivity $this;

    @Override
    protected void init() {
        super.init();
        $this = this;
        setContentView(R.layout.layout_login);
        myHandler = new MyHandler(this);
    }

    @Override
    protected void initView() {
        super.initView();
        setActionBarLayout(false, -1, this);
        //btnForgetPassword.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
//        btnRegister.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
//        btnRegister.getPaint().setAntiAlias(true);//抗锯齿


        api = WXAPIFactory.createWXAPI(this, IConstants.APPID_WX, false);
        api.registerApp(IConstants.APPID_WX);
        mUnionId = "";

        mHandler = new LoginHandler(LoginActivity.this);
    }

    @OnClick({R.id.layout_login_submit_tv, R.id.layout_login_wechat_iv})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.layout_login_submit_tv:
//                    activityStartUtils.skipActivity(MainActivity.class);
//                    Intent intent = new Intent(this, MainActivity.class);
//                    this.startActivity(intent);
//                    finish();
                String mPhone = editAccount.getText().toString().trim();
                if (StringUtils.isMobile(mPhone) && !TextUtils.isEmpty(etCode.getText().toString())) {
                    doLogin();
                } else {
                    new SVProgressHUD(mContext).showErrorWithStatus(getString(R.string.account_error));
                }
                break;
            case R.id.layout_login_wechat_iv:
                wxLogin();
                break;
        }
    }

    private void doLogin() {
        mAppHelper.apiService().loginApp(editAccount.getText().toString(), etCode.getText().toString()).enqueue(new BaseCallback<ApiResponse<LoginResponseBean>>() {
            @Override
            public void onSuccess(Call<ApiResponse<LoginResponseBean>> call, Response<ApiResponse<LoginResponseBean>> response) {
                LoginBean bean = LoginBean.dataChange(response.body().getData());
                Session.setSessionKey(bean.getToken());
                Session.setUserPhone(bean.getPhone());
                Session.setUserIsLogin(true);
                SignHelper.initToken(Session.getSessionKey());
                activityStartUtils.skipActivity(MainActivity.class);
                JPushInterface.setAlias($this, 1, editAccount.getText().toString().trim());
                if (JPushInterface.isPushStopped($this)) {
                    JPushInterface.resumePush($this);
                }
            }

            @Override
            public void onTokenTimeOut() {
            }
        });
    }

    private void wxLogin() {
        if (SystemUtils.isWeixinAvilible(mContext)) {
            final SendAuth.Req req = new SendAuth.Req();
            req.scope = "snsapi_userinfo";
            req.transaction = IConstants.APPID_WX;
            req.state = "wechat_sdk_gym_login";
            api.sendReq(req);

        } else {
            ToastUtil.show(mContext, R.string.ssdk_wechat_client_inavailable);
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        Log.e("Login_onActivityResult", String.valueOf(requestCode));
    }

    class LoginHandler extends Handler {
        private Context mContext;

        public LoginHandler(Context _context) {
            this.mContext = _context;
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    L.e("登录  " + msg.obj.toString());
                    mUnionId = msg.obj.toString();
                    toLoginByWx(mUnionId);
                    break;
                case 1:

                    new AlertDialog.Builder(mContext)
                            .setTitle("提示")
                            .setMessage("检测到您尚未绑定微信，您可以：")
                            .setPositiveButton("注册新账号",
                                    new DialogInterface.OnClickListener() {
                                        public void onClick(
                                                DialogInterface dialoginterface, int i) {
                                            //
                                            dialoginterface.dismiss();
                                            Bundle bdl = new Bundle();
                                            bdl.putString("wx_id", mUnionId);
                                            activityStartUtils.showActivity((LoginActivity) mContext, RegisterActivity.class, bdl);
                                        }
                                    })
                            .setNegativeButton("绑定已有账号",
                                    new DialogInterface.OnClickListener() {
                                        public void onClick(
                                                DialogInterface dialoginterface, int i) {
                                            //
                                            dialoginterface.dismiss();
                                        }
                                    }).show();
                    break;
            }
        }
    }

    @OnClick(RES_ID_CODE_BTN)
    public void sendCode() {
        String mobile;
        if (!runningOne && StringUtils.isMobile(mobile = editAccount.getText().toString())) {
            tvCode.setEnabled(false);
            mAppHelper.apiService().getPhoneCode(mobile).enqueue(new BaseCallback<ApiResponse<Object>>() {
                @Override
                public void onSuccess(Call<ApiResponse<Object>> call, Response<ApiResponse<Object>> response) {
                    if (count == 0) {
                        count = MyHandler.DEFAULT_COUNT;
                        new Thread() {
                            @Override
                            public void run() {
                                super.run();
                                runningOne = true;
                                while (count > 0) {
                                    count = count - 1;
                                    myHandler.sendEmptyMessage(1);
                                    try {
                                        Thread.sleep(1000);
                                    } catch (InterruptedException e) {
                                        // TODO Auto-generated catch block
                                        e.printStackTrace();
                                    }
                                }
                                runningOne = false;
                                myHandler.sendEmptyMessage(0);
                            }
                        }.start();
                    }
                }

                @Override
                public void onError(Call<ApiResponse<Object>> call, Throwable t) {
                    super.onError(call, t);
                    tvCode.setEnabled(true);
                }

                @Override
                public void onTokenTimeOut() {
                }
            });
        } else {
            new SVProgressHUD(mContext).showErrorWithStatus(getString(R.string.account_error));
        }
    }

    private void toLoginByWx(String wx_id) {
        L.e("登录 请求后台" + wx_id);
        mAppHelper.apiService().appGetLogin(wx_id, "2").enqueue(new BaseCallback<ApiResponse<WxLoginBean>>() {
            @Override
            public void onSuccess(Call<ApiResponse<WxLoginBean>> call, Response<ApiResponse<WxLoginBean>> response) {

                new SVProgressHUD(LoginActivity.this).showSuccessWithStatus("登录成功");
                Session.setSessionKey(response.body().getData().getTyg_token());
                Session.setUserIsLogin(true);
                SignHelper.initToken(Session.getSessionKey());
                if (!TextUtils.isEmpty(response.body().getData().getTyg_phone())) {
                    L.e(TAG, response.body().getData().getTyg_phone());
                    JPushInterface.setAlias($this, 1, response.body().getData().getTyg_phone());
                    if (JPushInterface.isPushStopped($this)) {
                        JPushInterface.resumePush($this);
                    }
                }
                (new ActivityStartUtils(LoginActivity.this)).skipActivity(MainActivity.class);
            }

            @Override
            public void onError(Call<ApiResponse<WxLoginBean>> call, Throwable t) {
                super.onError(call, t);
                new SVProgressHUD(LoginActivity.this).showErrorWithStatus(t.getMessage());
            }

            @Override
            public void onTokenTimeOut() {
            }

            @Override
            public void onFailure(Call<ApiResponse<WxLoginBean>> call, Throwable t) {
                super.onFailure(call, t);
                new SVProgressHUD(LoginActivity.this).showSuccessWithStatus("请求失败");
                Message msg = new Message();
                msg.what = 1;
                msg.obj = mUnionId;
                LoginActivity.mHandler.sendMessage(msg);
            }
        });


    }

    public static void logout(Context context, String message) {
        Session.clearShareP();
        if (!TextUtils.isEmpty(message)) {
            ToastUtil.show(context, message);
        }
        context.startActivity(new Intent(context, LoginActivity.class));
        AppHelper.clearActivity();
        JPushInterface.deleteAlias(context, 1);
    }

    private static class MyHandler extends android.os.Handler {
        WeakReference<LoginActivity> mActivity;
        public static final int MSG_FIRST = 0;
        public static final int MSG_COUNT = 1;
        public static final int DEFAULT_COUNT = 60;
        private static final int BG_ABLE = R.drawable.yellow_border;
        private static final int BG_DISABLE = R.drawable.gray_disable_border;

        public MyHandler(LoginActivity activity) {
            mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            final LoginActivity mf = mActivity.get();
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_FIRST:
                    mf.tvCode.setText("重新发送");
                    mf.tvCode.setEnabled(true);
                    mf.tvCode.setTextColor(Color.BLACK);
                    mf.tvCode.setBackgroundResource(BG_ABLE);
                    break;
                case MSG_COUNT:
                    mf.tvCode.setEnabled(false);
                    mf.tvCode.setText(mf.count + "秒后再次发送");
                    mf.tvCode.setTextColor(COLOR_GRAY_70);
                    mf.tvCode.setBackgroundResource(BG_DISABLE);
                    break;
            }
        }

    }

    public static void logout(Context context) {
        logout(context, null);
    }
}

